import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';
import {
  Box,
  Container,
  Grid,
  Typography,
  Paper,
  Tabs,
  Tab,
  Button,
  Card,
  CardContent,
  CardActions,
  Chip,
  Divider,
  LinearProgress,
  List,
  ListItem,
  ListItemText,
  ListItemIcon
} from '@mui/material';
import {
  Code as CodeIcon,
  Description as DescriptionIcon,
  Assignment as AssignmentIcon,
  CheckCircle as CompletedIcon,
  Star as StarIcon,
  ArrowBack as ArrowBackIcon
} from '@mui/icons-material';
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { atomDark } from 'react-syntax-highlighter/dist/esm/styles/prism';

import { RootState } from '../redux/store';
import { AppDispatch } from '../redux/store';
import { getPatternById } from '../redux/slices/patternSlice';
import { getPatternProgress } from '../redux/slices/progressSlice';
import { getChallengesByPattern } from '../redux/slices/challengeSlice';
import { addAlert } from '../redux/slices/uiSlice';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

const TabPanel = (props: TabPanelProps) => {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`pattern-tabpanel-${index}`}
      aria-labelledby={`pattern-tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
    </div>
  );
};

const PatternDetails: React.FC = () => {
  const { patternId } = useParams<{ patternId: string }>();
  const navigate = useNavigate();
  const dispatch = useDispatch<AppDispatch>();
  const [tabValue, setTabValue] = useState(0);
  const { t } = useTranslation();

  const { currentPattern, loading: patternLoading } = useSelector((state: RootState) => state.patterns);
  const { patternProgress, loading: progressLoading } = useSelector((state: RootState) => state.progress);
  const { challenges, loading: challengesLoading } = useSelector((state: RootState) => state.challenges);

  useEffect(() => {
    if (patternId) {
      dispatch(getPatternById(patternId));
      dispatch(getPatternProgress(patternId));
      dispatch(getChallengesByPattern(patternId));
    }
  }, [dispatch, patternId]);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  const handleStartChallenge = (challengeId: string) => {
    navigate(`/challenges/${challengeId}`);
  };

  if (patternLoading || progressLoading || challengesLoading || !currentPattern) {
    return (
      <Box sx={{ width: '100%', mt: 4 }}>
        <LinearProgress />
      </Box>
    );
  }

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Button
        startIcon={<ArrowBackIcon />}
        onClick={() => navigate('/dashboard')}
        sx={{ mb: 2 }}
      >
        {t('patterns.details.backToDashboard')}
      </Button>
      
      <Paper sx={{ mb: 4, p: 3 }}>
        <Grid container spacing={2}>
          <Grid item xs={12} md={8}>
            <Typography variant="h4" component="h1" gutterBottom>
              {t(`patterns.names.${currentPattern.name}`, { defaultValue: currentPattern.name })}
            </Typography>
            <Chip
              label={t(`patterns.categories_en.${currentPattern.category}`, { defaultValue: currentPattern.category })}
              color={
                currentPattern.category === 'Creational'
                  ? 'primary'
                  : currentPattern.category === 'Structural'
                  ? 'secondary'
                  : 'info'
              }
              sx={{ mr: 1 }}
            />
          </Grid>
          <Grid item xs={12} md={4} sx={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
            {patternProgress?.some(p => p.completed) && (
              <Chip
                icon={<StarIcon />}
                label={t('patterns.details.completed')}
                color="success"
                variant="outlined"
              />
            )}
          </Grid>
        </Grid>
      </Paper>

      <Box sx={{ width: '100%' }}>
        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs value={tabValue} onChange={handleTabChange} aria-label="pattern tabs">
            <Tab icon={<DescriptionIcon />} label={t('patterns.details.tabs.description')} />
            <Tab icon={<CodeIcon />} label={t('patterns.details.tabs.sampleCode')} />
            <Tab icon={<AssignmentIcon />} label={t('patterns.details.tabs.challenges')} />
          </Tabs>
        </Box>
        
        <TabPanel value={tabValue} index={0}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <Typography variant="h6" gutterBottom>{t('patterns.details.sections.intent')}</Typography>
              <Typography paragraph>
                {t(`patterns.content.${currentPattern.name}.intent`, { defaultValue: currentPattern.intent })}
              </Typography>
            </Grid>
            
            <Grid item xs={12}>
              <Typography variant="h6" gutterBottom>{t('patterns.details.sections.description')}</Typography>
              <Typography paragraph>
                {t(`patterns.content.${currentPattern.name}.description`, { defaultValue: currentPattern.description })}
              </Typography>
            </Grid>
            
            <Grid item xs={12}>
              <Typography variant="h6" gutterBottom>{t('patterns.details.sections.applicability')}</Typography>
              <Typography paragraph>
                {t(`patterns.content.${currentPattern.name}.applicability`, { defaultValue: currentPattern.applicability })}
              </Typography>
            </Grid>
            
            <Grid item xs={12}>
              <Typography variant="h6" gutterBottom>{t('patterns.details.sections.structure')}</Typography>
              <Typography paragraph>
                {t(`patterns.content.${currentPattern.name}.structure`, { defaultValue: currentPattern.structure })}
              </Typography>
            </Grid>
            
            <Grid item xs={12}>
              <Typography variant="h6" gutterBottom>{t('patterns.details.sections.participants')}</Typography>
              <Typography paragraph>
                {t(`patterns.content.${currentPattern.name}.participants`, { defaultValue: currentPattern.participants })}
              </Typography>
            </Grid>
            
            <Grid item xs={12}>
              <Typography variant="h6" gutterBottom>{t('patterns.details.sections.collaborations')}</Typography>
              <Typography paragraph>
                {t(`patterns.content.${currentPattern.name}.collaborations`, { defaultValue: currentPattern.collaborations })}
              </Typography>
            </Grid>
            
            <Grid item xs={12}>
              <Typography variant="h6" gutterBottom>{t('patterns.details.sections.consequences')}</Typography>
              <Typography paragraph>
                {t(`patterns.content.${currentPattern.name}.consequences`, { defaultValue: currentPattern.consequences })}
              </Typography>
            </Grid>
            
            <Grid item xs={12}>
              <Typography variant="h6" gutterBottom>{t('patterns.details.sections.implementation')}</Typography>
              <Typography paragraph>
                {t(`patterns.content.${currentPattern.name}.implementation`, { defaultValue: currentPattern.implementation })}
              </Typography>
            </Grid>
            
            <Grid item xs={12}>
              <Typography variant="h6" gutterBottom>{t('patterns.details.sections.knownUses')}</Typography>
              <Typography paragraph>
                {t(`patterns.content.${currentPattern.name}.knownUses`, { defaultValue: currentPattern.knownUses })}
              </Typography>
            </Grid>
            
            <Grid item xs={12}>
              <Typography variant="h6" gutterBottom>{t('patterns.details.sections.relatedPatterns')}</Typography>
              <List>
                {currentPattern.relatedPatterns.map((pattern, index) => (
                  <ListItem key={index}>
                    <ListItemIcon>
                      <StarIcon />
                    </ListItemIcon>
                    <ListItemText primary={t(`patterns.names.${pattern}`, { defaultValue: pattern })} />
                  </ListItem>
                ))}
              </List>
            </Grid>
          </Grid>
        </TabPanel>
        
        <TabPanel value={tabValue} index={1}>
          <Paper sx={{ p: 2 }}>
            <SyntaxHighlighter language="java" style={atomDark}>
              {t(`patterns.sampleCode.${currentPattern.name}`, { defaultValue: currentPattern.sampleCode })}
            </SyntaxHighlighter>
          </Paper>
        </TabPanel>
        
        <TabPanel value={tabValue} index={2}>
          <Grid container spacing={3}>
            {challenges.map((challenge) => {
              const progress = patternProgress?.find(p => p.challenge._id === challenge._id);
              const isCompleted = progress?.completed || false;
              const rating = progress?.evaluation?.rating || null;
              
              return (
                <Grid item xs={12} md={6} key={challenge._id}>
                  <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                    <CardContent sx={{ flexGrow: 1 }}>
                      <Box display="flex" justifyContent="space-between" alignItems="center" mb={1}>
                        <Typography variant="h6" component="h2">
                          {challenge.title}
                        </Typography>
                        {isCompleted && (
                          <CompletedIcon color="success" />
                        )}
                      </Box>
                      
                      <Chip
                        label={t(`challenge.levels.${challenge.level}`)}
                        size="small"
                        color={
                          challenge.level === 'beginner'
                            ? 'primary'
                            : challenge.level === 'intermediate'
                            ? 'secondary'
                            : 'error'
                        }
                        sx={{ mb: 2 }}
                      />
                      
                      <Typography variant="body2" paragraph>
                        {challenge.description.substring(0, 150)}...
                      </Typography>
                      
                      {rating && (
                        <Box mt={2}>
                          <Typography variant="body2" color="text.secondary">
                            {t('patterns.details.challenge.rating')}
                          </Typography>
                          <Chip
                            label={t(`challenge.ratings.${rating}`)}
                            size="small"
                            color={
                              rating === 'Excellent'
                                ? 'success'
                                : rating === 'Good'
                                ? 'primary'
                                : rating === 'Satisfactory'
                                ? 'info'
                                : 'error'
                            }
                          />
                        </Box>
                      )}
                    </CardContent>
                    <CardActions>
                      <Button
                        size="small"
                        onClick={() => handleStartChallenge(challenge._id)}
                      >
                        {isCompleted 
                          ? t('patterns.details.challenge.reviewChallenge') 
                          : t('patterns.details.challenge.startChallenge')}
                      </Button>
                    </CardActions>
                  </Card>
                </Grid>
              );
            })}
          </Grid>
        </TabPanel>
      </Box>
    </Container>
  );
};

export default PatternDetails; 